package com.magicborrow.activity;

import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ImageView;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.magicborrow.Constants;
import com.magicborrow.R;
import com.magicborrow.utils.VolleyTool;
import com.magicborrow.view.MyImageViewPager;

import java.util.ArrayList;


import uk.co.senab.photoview.PhotoView;
import uk.co.senab.photoview.PhotoViewAttacher;

/**
 * 活动/动态的-图片详情 <br>
 * 按计划，活动/动态的图片在一齐，会话的图片独立开来
 *
 * @version 2.0 可以多图(UrlList),有下标提示,可以保存图片<br>
 *          3.0 实现先显示缩位图，再显示大图
 *          4.0 
 * @author XieWenjun
 *
 */

/**
 * 图片查看器
 * 	之前只为活动/动态服务，现在作为全局服务
 * @author XieWenjun
 * @version
 *       1.0, 2013-12-27 上午11:15:29
 */
public class CommonViewPagerActivity extends BaseActivity implements ImageLoader.ImageListener{

	public static CommonViewPagerActivity instance = null;

	private MyImageViewPager viewPager;
	private TextView textView1;
	private TextView textView2;

	private int position;
	private ArrayList<String> imageUrlList;

	/**
	 * 在这里添加了启动动画
	 */
	public static void launcher(Context context, ArrayList<String> imageUrlList, int position) {
		/*Intent intent = new Intent(context, CommonViewPagerActivity.class);
		intent.putExtra("netImageUrls", imageUrlList);
		intent.putExtra("position", position);
		context.startActivity(intent);
		((Activity)context).overridePendingTransition(R.anim.activity_imageviewpager_in, R.anim.activity_nothing);*/
	}

	/**
	 * 退出动画
	 */
	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {
		if (event.getAction() == KeyEvent.ACTION_UP && event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
			finish();
			overridePendingTransition(R.anim.activity_nothing, R.anim.activity_imageviewpager_out);
			return true;
		}
		return super.dispatchKeyEvent(event);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
       // requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_common_view_viewpager);
		setHasTitle(false);

		instance = this;
		if (getIntent().hasExtra("netImageUrls")) {
			position = getIntent().getIntExtra("position", 0);
			imageUrlList = getIntent().getStringArrayListExtra("netImageUrls");
		}

		// 自定义ViewPager
		viewPager = (MyImageViewPager) findViewById(R.id.myImageViewPager);
		viewPager.setOffscreenPageLimit(3);
		viewPager.setAdapter(new SamplePagerAdapter());
		viewPager.setCurrentItem(position, false);

		// 当前下标/总数(例子：2/10)
		textView1 = (TextView) findViewById(R.id.textView1);
		textView2 = (TextView) findViewById(R.id.textView2);
		textView2.setText(imageUrlList.size() + "");
		if (imageUrlList.size() <= 1) {
			findViewById(R.id.linearLayout).setVisibility(View.GONE);
		}
	}

    @Override
    public void onResponse(ImageLoader.ImageContainer imageContainer, boolean b) {

    }

    @Override
    public void onErrorResponse(VolleyError volleyError) {

    }

    /**
	 * 图片适配器
	 */
	class SamplePagerAdapter extends PagerAdapter {

		@Override
		public void startUpdate(ViewGroup container) {
			super.startUpdate(container);
			// 切换时修改下标
			textView1.setText((viewPager.getCurrentItem() + 1) + "");
		}

		@Override
		public int getCount() {
			return imageUrlList.size();
		}

		@Override
		public View instantiateItem(ViewGroup container, int position) {
			// 第三方PhotoView,嵌套在ViewPager中,支持缩放什么的
			final PhotoView photoView = new PhotoView(container.getContext());
			photoView.setMaxScale(10);

			// 图片地址
			String bigImageUrl = imageUrlList.get(position);
			photoView.setTag(bigImageUrl);

			// TODO 图片来源[ Res, SDCard, Net; (Assest不作考虑)]
			// 先从本地取数据，取不到就拿网络的，不判断
			if (bigImageUrl.contains("store")) {
				com.nostra13.universalimageloader.core.ImageLoader.getInstance().displayImage(Constants.ADDRESS+bigImageUrl, photoView);

			} else {

				com.nostra13.universalimageloader.core.ImageLoader.getInstance().displayImage("file://" + bigImageUrl, photoView);

			}
			/*if(bigImageUrl.contains("http")){

            VolleyTool.getImageLoader().get( bigImageUrl, new ImageLoader.ImageListener() {
				@Override
				public void onResponse(ImageLoader.ImageContainer imageContainer, boolean b) {
					if (imageContainer != null && imageContainer.getBitmap() != null) {
						photoView.setImageBitmap(imageContainer.getBitmap());
					} else {
						photoView.setImageResource(R.mipmap.empty_photo);
					}

				}

				@Override
				public void onErrorResponse(VolleyError volleyError) {
					photoView.setImageResource(R.mipmap.empty_photo);
				}
			});}else {
				Bitmap bmp = ImageUtil.readFile(bigImageUrl, UIHelper.getScreenWidth(CommonViewPagerActivity.this),UIHelper.getScreenHeight(CommonViewPagerActivity.this));
				photoView.setImageBitmap(bmp);
			}*/
		/*	Bitmap bitmap = null;
			bitmap = PhotoUtil.decodeFile(CommonViewPagerActivity.this, bigImageUrl);
			if (bitmap != null) {
				photoView.setImageBitmap(bitmap);
			} else {
				ImageLoadUtil.loadImage(photoView, bigImageUrl, R.drawable.empty_photo);
			}*/

			// 轻敲退出
			photoView.setOnPhotoTapListener(new PhotoViewAttacher.OnPhotoTapListener() {
				@Override
				public void onPhotoTap(View arg0, float arg1, float arg2) {
					if (instance != null) {
						finish();
						overridePendingTransition(R.anim.activity_nothing, R.anim.activity_imageviewpager_out);
					}
				}
			});

			/*// 长按保存     干掉长安保存
			photoView.setOnLongClickListener(new View.OnLongClickListener() {
				@Override
				public boolean onLongClick(View v) {
					AlertDialog.Builder builder = new AlertDialog.Builder(CommonViewPagerActivity.this);
					final CharSequence[] items = { "保存图片" };

					builder.setTitle("选择操作");
					builder.setItems(items, new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int item) {
							if (items[item].equals("保存图片")) {
								PhotoUtil.saveFile(CommonViewPagerActivity.this, (String) photoView.getTag());
							}
						}
					});
					builder.show();
					return false;
				}
			});*/
			container.addView(photoView, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
			return photoView;
		}

		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
			container.removeView((View) object);
		}

		@Override
		public boolean isViewFromObject(View view, Object object) {
			return view == object;
		}

	}


	/**
	 * 当设备配置信息有改动（比如屏幕方向的改变，实体键盘的推开或合上等）时， 并且如果此时有activity正在运行，系统会调用这个函数。 注意：
	 * onConfigurationChanged只会监测应用程序在AnroidMainifest.xml中通过
	 * android:configChanges="xxxx"指定的配置类型的改动；
	 * 而对于其他配置的更改，则系统会onDestroy()当前Activity，然后重启一个新的Activity实例。
	 */
	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		// 检测屏幕的方向：纵向或横向
		if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
			// 当前为横屏， 在此处添加额外的处理代码
		} else if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
			// 当前为竖屏， 在此处添加额外的处理代码
		}

		// 检测实体键盘的状态：推出或者合上
		if (newConfig.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_NO) {
			// 实体键盘处于推出状态，在此处添加额外的处理代码
		} else if (newConfig.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_YES) {
			// 实体键盘处于合上状态，在此处添加额外的处理代码
		}
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
	}
}